package com.config.captcha;

import com.common.Const;
import com.utils.RedisUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码过滤器
 */
public class CaptchaFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtil redisUtil;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        String url = httpServletRequest.getRequestURI();
        //判断是否是登录请求
        if("/login".equals(url) && httpServletRequest.getMethod().equals("POST")) {
            //校验验证码
            try {
                validateCaptcha(httpServletRequest);

            } catch (Exception e) {
                throw new CaptchaException("验证码错误！");
            }
            //如果不正确，是否要加认证失败处理器
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    /**
     * 校验验证码
     * @param httpServletRequest
     * @return
     */
    private void validateCaptcha(HttpServletRequest httpServletRequest) {

        String codeKey = httpServletRequest.getParameter("codeKey");
        String captchaImg = httpServletRequest.getParameter("captchaImg");

        if (StringUtils.isEmpty(codeKey) || StringUtils.isEmpty(captchaImg)) {
            throw new CaptchaException("验证码错误!");
        }

        if (!captchaImg.equals(redisUtil.hget(Const.CAPTCHA_KEY, codeKey))) {
            throw new CaptchaException("验证码错误!");
        }
        //一次性使用, 需要删除
        redisUtil.hdel(Const.CAPTCHA_KEY, codeKey);
    }
}
